import { Observable } from 'rxjs'
import { tap, } from 'rxjs/operators'
export const getES = (obj, key) => {
  const source = new Observable(observe => {
    obj[key] = (...args) => observe.next(args);
    return source;
  });
  source.subscribe();
  return source;
};
export const getUserMediaSource = (obj = { video: false, audio: false }) => {
  const observable = new Observable(observe => {
    const fn = res => observe.next(res);
    // 本地ip打开失败，本地localhost打开成功
    navigator.getUserMedia(obj, fn, fn);
  });
  return observable;
};
export const createPeerConnection = () => {
  const myPeerConnection = new RTCPeerConnection({
    iceServers: [
      // Information about ICE servers - Use your own!
      {
        urls: 'turn:' + location.hostname, // A TURN server
        username: 'webrtc',
        credential: 'turnserver',
      },
    ],
  });
  myPeerConnection.negotiationneededSource = getES(
    myPeerConnection,
    'onnegotiationneeded',
  );
  myPeerConnection.negotiationneededSource
    .pipe(tap(() => console.log(myPeerConnection.signalingState)))
    .subscribe();
  myPeerConnection.candidateSource = getES(myPeerConnection, 'onicecandidate');
  myPeerConnection.trackSource = getES(myPeerConnection, 'ontrack');
  return myPeerConnection;
};